/**
 * @swagger
 * components:
 *   schemas:
 *     Certificate:
 *       type: object
 *       required:
 *         - sequence_number
 *         - fields
 *       properties:
 *         id:
 *           type: integer
 *           description: 证书ID
 *         sequence_number:
 *           type: string
 *           description: 证书序号
 *         fields:
 *           type: array
 *           description: 证书字段
 *           items:
 *             type: object
 *             properties:
 *               field_name:
 *                 type: string
 *                 description: 字段唯一标识符
 *               name:
 *                 type: string
 *                 description: 字段显示名称
 *               description:
 *                 type: string
 *                 description: 字段内容
 *         custom_text:
 *           type: string
 *           description: 自定义文本
 *         qr_code_path:
 *           type: string
 *           description: 二维码路径
 *         created_at:
 *           type: string
 *           format: date-time
 *           description: 创建时间
 *         updated_at:
 *           type: string
 *           format: date-time
 *           description: 更新时间
 */

const path = require('path');
const fs = require('fs').promises;
const fsSync = require('fs');  // 添加同步版本的 fs
const QRCode = require('qrcode');
const Certificate = require('../models/Certificate');
const Field = require('../models/Field');
const logger = require('../utils/logger');
const { Op } = require('sequelize');
const archiver = require('archiver');
const Sequelize = require('sequelize');
const sequelize = require('../config/database');
const RedisHelper = require('../utils/redisHelper');
const fileService = require('../services/fileService');
const redis = require('../config/redis');

// 缓存键前缀
const CACHE_KEY = {
  CERTIFICATE: 'cert:',
  CERTIFICATE_LIST: 'cert:list:',
  FIELD_LIST: 'field:list'
};

// 缓存时间（秒）
const CACHE_TIME = {
  CERTIFICATE: 3600, // 单个证书缓存1小时
  CERTIFICATE_LIST: 300, // 列表缓存5分钟
  FIELD_LIST: 3600 * 24 // 字段列表缓存24小时
};

// 生成证书列表缓存键
const generateListCacheKey = (page, limit, certNumber) => {
  return `${CACHE_KEY.CERTIFICATE_LIST}${page}:${limit}:${certNumber || 'all'}`;
};

// 生成单个证书缓存键
const generateCertCacheKey = certNumber => {
  return `${CACHE_KEY.CERTIFICATE}${certNumber}`;
};

// 清除证书相关的所有缓存
const clearCertificateCache = async () => {
  // 清除旧缓存
  await RedisHelper.delByPattern(`${CACHE_KEY.CERTIFICATE}*`);
  await RedisHelper.delByPattern(`${CACHE_KEY.CERTIFICATE_LIST}*`);

  // 获取总记录数
  const total = await Certificate.count();
  const pageSize = 10;
  const totalPages = Math.ceil(total / pageSize);
  
  // 预热前3页的缓存
  const pagesToWarmup = Math.min(3, totalPages);
  
  for(let page = 1; page <= pagesToWarmup; page++) {
    const offset = (page - 1) * pageSize;
    
    const { count, rows } = await Certificate.findAndCountAll({
      offset,
      limit: pageSize,
      order: [['sequence_number', 'ASC']]
    });

    const result = {
      total: count,
      items: rows.map(cert => ({
        ...cert.toJSON(),
        qr_code_url: cert.qr_code_path ? 
          (cert.qr_code_path.startsWith('http') ? cert.qr_code_path : `/api/uploads/${cert.qr_code_path}`) : 
          null
      }))
    };

    // 设置新缓存
    const cacheKey = generateListCacheKey(page, pageSize, '');
    await RedisHelper.set(cacheKey, result, CACHE_TIME.CERTIFICATE_LIST);
  }
  
  // 如果总页数大于预热页数，预热最后一页
  if(totalPages > pagesToWarmup) {
    const lastPage = totalPages;
    const offset = (lastPage - 1) * pageSize;
    
    const { count, rows } = await Certificate.findAndCountAll({
      offset,
      limit: pageSize,
      order: [['sequence_number', 'ASC']]
    });

    const result = {
      total: count,
      items: rows.map(cert => ({
        ...cert.toJSON(),
        qr_code_url: cert.qr_code_path ? 
          (cert.qr_code_path.startsWith('http') ? cert.qr_code_path : `/api/uploads/${cert.qr_code_path}`) : 
          null
      }))
    };

    // 设置最后一页的缓存
    const cacheKey = generateListCacheKey(lastPage, pageSize, '');
    await RedisHelper.set(cacheKey, result, CACHE_TIME.CERTIFICATE_LIST);
  }
};

// 生成序号
const generateSequenceNumber = async () => {
  // 获取最大序号
  const lastCert = await Certificate.findOne({
    order: [['sequence_number', 'DESC']]
  });

  // 如果存在证书，获取最后一个序号并加1，否则从1开始
  let sequence = 1;
  if (lastCert && lastCert.sequence_number) {
    sequence = parseInt(lastCert.sequence_number) + 1;
  }

  // 返回4位数字格式：0001
  return String(sequence).padStart(4, '0');
};

// 获取证书编号
const getCertNumber = (fields) => {
  const certNumberField = fields.find(f => f.field_name === 'cert_number');
  return certNumberField ? certNumberField.description : '';
};

// 生成二维码
const generateQRCode = async (certificate) => {
  const qrcodesDir = path.join(__dirname, '../uploads/qrcodes');
  try {
    await fs.mkdir(qrcodesDir, { recursive: true });
  } catch (error) {
    if (error.code !== 'EEXIST') {
      throw error;
    }
  }

  // 使用证书编号作为文件名
  const certNumber = getCertNumber(certificate.fields);
  const qrCodeFileName = `${certNumber}.png`;
  const qrCodePath = path.join(qrcodesDir, qrCodeFileName);
  const relativePath = `qrcodes/${qrCodeFileName}`;
  
  // 生成二维码，使用证书编号作为外链后缀
  const baseUrl = process.env.BASE_URL || 'http://localhost:3800';
  const certificateUrl = `${baseUrl}/view/${certNumber}`;
  
  // 生成二维码
  await QRCode.toFile(qrCodePath, certificateUrl, {
    width: 300,
    margin: 2,
    color: {
      dark: '#000000',
      light: '#ffffff'
    }
  });

  // 更新证书的二维码路径
  await certificate.update({ qr_code_path: relativePath });

  // 异步上传到对象存储，不阻塞主流程
  const qrCodeBuffer = await fs.readFile(qrCodePath);
  
  // 使用相对路径作为文件名
  const localUrl = `/api/uploads/${relativePath}`;
  fileService.saveFile(qrCodeBuffer, relativePath)
    .then(ossUrl => {
      // 如果返回的是对象存储URL，设置延迟切换
      if (ossUrl.startsWith('http')) {
        fileService.switchToOssUrl(relativePath, ossUrl);
      }
    })
    .catch(err => {
      logger.error('上传二维码到对象存储失败:', err);
    });
  
  return {
    fileName: qrCodeFileName,
    fileUrl: localUrl
  };
};

// 验证字段是否存在
const validateFields = async (fields) => {
  try {
    logger.info('开始验证字段:', fields);

    if (!Array.isArray(fields)) {
      logger.error('字段不是数组格式');
      throw new Error('字段必须是数组格式');
    }

    // 检查必填字段
    const missingFields = fields.filter(f => !f.field_name || !f.description);
    if (missingFields.length > 0) {
      logger.error('字段缺少必要属性:', missingFields);
      throw new Error('字段格式不正确，必须包含 field_name 和 description');
    }

    const fieldNames = fields.map(f => f.field_name);
    logger.info('查询字段名称:', fieldNames);

    const existingFields = await Field.findAll({
      where: {
        field_name: {
          [Op.in]: fieldNames
        }
      }
    });

    logger.info('数据库中找到的字段:', existingFields.map(f => f.field_name));

    const existingFieldNames = existingFields.map(f => f.field_name);
    const invalidFieldNames = fieldNames.filter(name => !existingFieldNames.includes(name));

    if (invalidFieldNames.length > 0) {
      logger.error('发现无效的字段名称:', invalidFieldNames);
      throw new Error(`字段 ${invalidFieldNames.join(', ')} 不存在`);
    }

    // 返回带有完整字段信息的数据
    const validatedFields = fields.map(field => {
      const existingField = existingFields.find(f => f.field_name === field.field_name);
      return {
        ...field, // 保留前端传来的所有原始属性
        name: existingField.name // 用数据库中的 name 覆盖
      };
    });

    logger.info('字段验证成功:', validatedFields);
    return validatedFields;
  } catch (error) {
    logger.error('字段验证失败:', error);
    throw error;
  }
};

/**
 * @swagger
 * /api/certificates:
 *   get:
 *     summary: 获取证书列表
 *     description: 分页获取证书列表，支持按证书编号搜索
 *     tags: [证书管理]
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *           default: 1
 *         description: 页码
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *           default: 10
 *         description: 每页数量
 *       - in: query
 *         name: certNumber
 *         schema:
 *           type: string
 *         description: 证书编号（可选）
 *     responses:
 *       200:
 *         description: 成功返回证书列表
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 data:
 *                   type: object
 *                   properties:
 *                     total:
 *                       type: integer
 *                       description: 总记录数
 *                     items:
 *                       type: array
 *                       items:
 *                         $ref: '#/components/schemas/Certificate'
 */
exports.getCertificates = async (req, res) => {
  try {
    const { page = 1, limit = 10, certNumber } = req.query;
    // const cacheKey = generateListCacheKey(page, limit, certNumber);
    
    // // 尝试从缓存获取
    // const cachedData = await RedisHelper.get(cacheKey);
    // if (cachedData) {
    //   logger.info('从缓存获取证书列表');
    //   return res.json({
    //     code: 200,
    //     data: cachedData
    //   });
    // }

    const offset = (page - 1) * limit;
    
    const where = {};
    if (certNumber) {
      where[sequelize.Op.and] = [
        sequelize.literal(`JSON_CONTAINS(fields, '{"field_name": "cert_number", "description": "${certNumber}"}')`)
      ];
    }
    
    const { count, rows } = await Certificate.findAndCountAll({
      where,
      offset,
      limit: parseInt(limit),
      order: [['sequence_number', 'ASC']]
    });
    
    // 添加二维码URL
    const items = rows.map(cert => {
      const fields = Array.isArray(cert.fields) ? cert.fields : JSON.parse(cert.fields);
      const certNumberField = fields.find(f => f.field_name === 'cert_number');
      return {
        ...cert.toJSON(),
        qr_code_url: cert.qr_code_path ? 
          (cert.qr_code_path.startsWith('http') || cert.qr_code_path.startsWith('https') ? cert.qr_code_path : `/api/uploads/${cert.qr_code_path}`) : 
          null,
        cert_number: certNumberField ? certNumberField.description : ''
      };
    });
    
    const result = {
      total: count,
      items
    };

    // // 设置缓存
    // await RedisHelper.set(cacheKey, result, CACHE_TIME.CERTIFICATE_LIST);
    
    res.json({
      code: 200,
      data: result
    });
  } catch (error) {
    logger.error('Get certificates error:', error);
    res.status(500).json({
      code: 500,
      message: '获取证书列表失败'
    });
  }
};

/**
 * @swagger
 * /api/certificates:
 *   post:
 *     summary: 创建证书
 *     description: 创建新的证书，包括字段信息和自定义文本
 *     tags: [证书管理]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - fields
 *             properties:
 *               fields:
 *                 type: array
 *                 items:
 *                   type: object
 *                   required:
 *                     - field_name
 *                     - description
 *                   properties:
 *                     field_name:
 *                       type: string
 *                       description: 字段唯一标识符
 *                     description:
 *                       type: string
 *                       description: 字段内容
 *               custom_text:
 *                 type: string
 *                 description: 自定义文本
 *     responses:
 *       200:
 *         description: 成功创建证书
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 data:
 *                   $ref: '#/components/schemas/Certificate'
 */
exports.createCertificate = async (req, res) => {
  try {
    const { fields, custom_text } = req.body;
    
    // 验证字段并获取带有 field_name 的字段数据
    const validatedFields = await validateFields(fields);
    
    // 生成序号
    const sequence_number = await generateSequenceNumber();
    
    // 创建证书
    const certificate = await Certificate.create({
      sequence_number,
      fields: validatedFields,
      custom_text: custom_text || ''  // 确保 custom_text 有值
    });
    
    // 生成二维码
    const qrCodeUrl = await generateQRCode(certificate);
    
    // 清除证书相关缓存
    await clearCertificateCache();
    
    res.json({
      code: 200,
      data: {
        ...certificate.toJSON(),
        qr_code_url: `/api/uploads/qrcodes/${qrCodeUrl}`  // 添加完整的URL
      }
    });
  } catch (error) {
    logger.error('Create certificate error:', error);
    res.status(500).json({
      code: 500,
      message: error.message || '创建证书失败'
    });
  }
};

/**
 * @swagger
 * /api/certificates/{id}:
 *   put:
 *     summary: 更新证书
 *     description: 更新指定ID的证书信息
 *     tags: [证书管理]
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: 证书ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               fields:
 *                 type: array
 *                 items:
 *                   type: object
 *                   properties:
 *                     field_name:
 *                       type: string
 *                       description: 字段标识
 *                     description:
 *                       type: string
 *                       description: 字段值
 *               custom_text:
 *                 type: string
 *                 description: 自定义文本
 *     responses:
 *       200:
 *         description: 成功更新证书
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 data:
 *                   $ref: '#/components/schemas/Certificate'
 *                 message:
 *                   type: string
 *                   example: 更新证书成功
 */
exports.updateCertificate = async (req, res) => {
  try {
    const { id } = req.params;
    const { fields, custom_text } = req.body;
    
    logger.info('开始更新证书:', { id, fields, custom_text });

    const certificate = await Certificate.findByPk(id);
    if (!certificate) {
      logger.warn('证书不存在:', id);
      return res.status(404).json({ 
        code: 404,
        message: '证书不存在' 
      });
    }

    // 验证字段并获取带有 field_name 的字段数据
    let validatedFields = certificate.fields;
    if (fields) {
      try {
        validatedFields = await validateFields(fields);
        logger.info('字段验证成功:', validatedFields);
      } catch (error) {
        logger.error('字段验证失败:', error);
        return res.status(400).json({
          code: 400,
          message: error.message
        });
      }
    }

    // 获取旧的证书编号和自定义文本
    const oldCustomText = certificate.custom_text;
    const oldCertNumber = getCertNumber(certificate.fields);
    const newCertNumber = fields ? getCertNumber(validatedFields) : oldCertNumber;
    
    logger.info('更新前后对比:', {
      oldCustomText,
      newCustomText: custom_text,
      oldCertNumber,
      newCertNumber
    });

    // 更新证书信息
    await certificate.update({
      fields: validatedFields,
      custom_text: custom_text !== undefined ? custom_text : certificate.custom_text
    });

    // 如果证书编号发生变化，需要重新生成二维码
    if (oldCertNumber !== newCertNumber) {
      logger.info('证书编号发生变化，需要重新生成二维码');
      // 删除旧的二维码文件
      if (certificate.qr_code_path) {
        // 使用旧的证书编号来构建旧二维码的路径
        const oldQrCodeFileName = `${oldCertNumber}.png`;
        const oldQrCodePath = path.join(__dirname, '../uploads/qrcodes', oldQrCodeFileName);
        
        if (fsSync.existsSync(oldQrCodePath)) {
          fsSync.unlinkSync(oldQrCodePath);
          // 同时从对象存储中删除
          const oldRelativePath = `qrcodes/${oldQrCodeFileName}`;
          await fileService.deleteFile(oldRelativePath);
        }
      }
      
      // 生成新的二维码
      await generateQRCode(certificate);
    }

    logger.info('证书更新成功:', certificate.id);

    // 更新成功后清除缓存
    await clearCertificateCache();
    
    res.json({
      code: 200,
      data: {
        ...certificate.toJSON(),
        qr_code_url: certificate.qr_code_path ? 
          `/uploads/${certificate.qr_code_path}` : 
          null
      },
      message: '更新证书成功'
    });
  } catch (error) {
    logger.error('更新证书失败:', error);
    res.status(500).json({ 
      code: 500,
      message: error.message || '更新证书失败'
    });
  }
};

/**
 * @swagger
 * /api/certificates/{id}:
 *   delete:
 *     summary: 删除证书
 *     description: 删除指定ID的证书
 *     tags: [证书管理]
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: 证书ID
 *     responses:
 *       200:
 *         description: 成功删除证书
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 message:
 *                   type: string
 *                   example: 删除证书成功
 */
exports.deleteCertificate = async (req, res) => {
  try {
    const { id } = req.params;

    const certificate = await Certificate.findByPk(id);
    if (!certificate) {
      return res.status(404).json({ message: '证书不存在' });
    }

    // 开启事务
    const t = await sequelize.transaction();

    try {
      // 1. 删除二维码文件
      if (certificate.qr_code_path) {
        const qrCodePath = path.join(__dirname, '../uploads', certificate.qr_code_path);
        try {
          await fs.access(qrCodePath);  // 检查文件是否存在
          await fs.unlink(qrCodePath);  // 删除文件
          logger.info('删除本地二维码文件成功:', qrCodePath);
        } catch (error) {
          if (error.code !== 'ENOENT') {
            logger.error('删除本地二维码文件失败:', error);
          }
        }

        // 尝试从对象存储中删除，忽略文件不存在的错误
        try {
          await fileService.deleteFile(certificate.qr_code_path);
          logger.info('从对象存储删除二维码文件成功');
        } catch (error) {
          logger.warn('从对象存储删除二维码文件失败 (可能文件不存在):', error);
        }
      }

      // 2. 删除证书
      await certificate.destroy({ transaction: t });

      // 3. 更新所有大于当前序号的证书的序号（减1）
      await Certificate.update(
        {
          sequence_number: Sequelize.literal('LPAD(CAST(CAST(sequence_number AS UNSIGNED) - 1 AS CHAR), 4, "0")')
        },
        {
          where: {
            sequence_number: {
              [Op.gt]: certificate.sequence_number
            }
          },
          transaction: t
        }
      );

      // 提交事务
      await t.commit();

      // 删除成功后清除缓存
      const singleCertKey = generateCertCacheKey(getCertNumber(certificate.fields));
      await RedisHelper.del(singleCertKey);
      await RedisHelper.delByPattern(`${CACHE_KEY.CERTIFICATE_LIST}*`);
      logger.info(`证书 (ID: ${id}) 及相关列表缓存已清除`);
      
      res.json({
        code: 200,
        message: '删除证书成功'
      });
    } catch (error) {
      await t.rollback();
      throw error;
    }
  } catch (error) {
    logger.error('删除证书失败:', error);
    res.status(500).json({ 
      message: '删除证书失败'
    });
  }
};

// 下载二维码
exports.downloadQRCode = async (req, res) => {
  try {
    const { id } = req.params;
    const certificate = await Certificate.findByPk(id);
    
    if (!certificate || !certificate.qr_code_path) {
      return res.status(404).json({
        code: 404,
        message: '二维码不存在'
      });
    }
    
    const filePath = path.join(__dirname, '../uploads', certificate.qr_code_path);
    
    // 设置正确的响应头，对文件名进行 URL 编码
    res.setHeader('Content-Type', 'image/png');
    res.setHeader('Content-Disposition', `attachment; filename=${encodeURIComponent(certificate.qr_code_path)}`);
    
    // 使用流发送文件
    const fileStream = fsSync.createReadStream(filePath);
    fileStream.pipe(res);
  } catch (error) {
    logger.error('Download QR code error:', error);
    res.status(500).json({
      code: 500,
      message: '下载二维码失败'
    });
  }
};

// 批量下载二维码
exports.batchDownloadQRCode = async (req, res) => {
  try {
    const { ids } = req.body;
    const certificates = await Certificate.findAll({
      where: {
        id: ids,
        qr_code_path: {
          [Op.not]: null
        }
      }
    });
    
    if (certificates.length === 0) {
      return res.status(404).json({
        code: 404,
        message: '没有可下载的二维码'
      });
    }
    
    // 创建临时目录
    const tempDir = path.join(__dirname, '../temp');
    if (!fs.existsSync(tempDir)) {
      fs.mkdirSync(tempDir, { recursive: true });
    }
    
    // 创建压缩文件
    const archive = archiver('zip', {
      zlib: { level: 9 } // 最高压缩级别
    });
    
    // 设置压缩文件名（使用当前时间戳）
    const timestamp = new Date().getTime();
    const zipFileName = `qrcodes_${timestamp}.zip`;
    const zipFilePath = path.join(tempDir, zipFileName);
    const output = fs.createWriteStream(zipFilePath);
    
    // 监听压缩完成事件
    output.on('close', () => {
      // 发送压缩文件
      res.download(zipFilePath, zipFileName, (err) => {
        if (err) {
          logger.error('Send zip file error:', err);
        }
        // 处理临时文件
        fs.unlinkSync(zipFilePath);
      });
    });
    
    archive.pipe(output);
    
    // 添加文件到压缩包
    for (const cert of certificates) {
      const filePath = path.join(__dirname, '../uploads', cert.qr_code_path);
      if (fs.existsSync(filePath)) {
        archive.file(filePath, { name: cert.qr_code_path });
      }
    }
    
    await archive.finalize();
  } catch (error) {
    logger.error('Batch download QR code error:', error);
    res.status(500).json({
      code: 500,
      message: '批量下载二维码失败'
    });
  }
};

// 前台查询证书
exports.getCertificate = async (req, res) => {
  try {
    const { certNumber } = req.params;
    const cacheKey = generateCertCacheKey(certNumber);
    
    // 尝试从缓存获取
    const cachedData = await RedisHelper.get(cacheKey);
    if (cachedData) {
      logger.info('从缓存获取证书详情');
      return res.json({
        code: 200,
        data: cachedData
      });
    }
    
    const certificate = await Certificate.findOne({
      where: sequelize.literal(`JSON_CONTAINS(fields, '{"field_name": "cert_number", "description": "${certNumber}"}')`)
    });

    if (!certificate) {
      return res.status(404).json({
        code: 404,
        message: '证书不存在'
      });
    }

    // 获取完整的字段信息
    const fieldNames = certificate.fields.map(f => f.field_name);
    const fieldInfos = await Field.findAll({
      where: {
        field_name: {
          [Op.in]: fieldNames
        }
      }
    });

    // 构建返回数据
    const certData = certificate.toJSON();
    certData.fields = certData.fields.map(field => {
      const fieldInfo = fieldInfos.find(f => f.field_name === field.field_name);
      return {
        field_name: field.field_name,
        name: fieldInfo.name,
        description: field.description
      };
    });

    // 移除敏感信息
    const { custom_text, ...finalData } = certData;
    const result = {
      ...finalData,
      qr_code_url: certificate.qr_code_path ? 
        `/api/uploads/${certificate.qr_code_path}` : 
        null
    };

    // 设置缓存
    await RedisHelper.set(cacheKey, result, CACHE_TIME.CERTIFICATE);
    
    res.json({
      code: 200,
      data: result
    });
  } catch (error) {
    logger.error('Get certificate error:', error);
    res.status(500).json({
      code: 500,
      message: '获取证书失败'
    });
  }
};

// 检查证书编号是否存在
exports.checkCertNumber = async (req, res) => {
  try {
    const { certNumber } = req.params;
    
    // 使用 MySQL 的 JSON 查询语法
    const certificate = await Certificate.findOne({
      where: sequelize.literal(`JSON_CONTAINS(fields, '{"field_name": "cert_number", "description": "${certNumber}"}')`)
    });
    
    res.json({
      code: 200,
      data: certificate ? {
        id: certificate.id,
        sequence_number: certificate.sequence_number
      } : null
    });
  } catch (error) {
    logger.error('Check certificate number error:', error);
    res.status(500).json({
      code: 500,
      message: '检查证书编号失败'
    });
  }
};

// 重新生成二维码
exports.regenerateQRCode = async (req, res) => {
  try {
    const { id } = req.params;
    
    const certificate = await Certificate.findByPk(id);
    if (!certificate) {
      return res.status(404).json({ message: '证书不存在' });
    }
    
    // 删除旧的二维码文件
    if (certificate.qr_code_path) {
      const oldQrCodePath = path.join(__dirname, '../uploads', certificate.qr_code_path);
      if (fsSync.existsSync(oldQrCodePath)) {
        fsSync.unlinkSync(oldQrCodePath);
      }
    }
    
    // 生成新的二维码
    const qrCodeData = await generateQRCode(certificate);
    
    // 清除相关缓存
    await clearCertificateCache();

    res.json({
      code: 200,
      data: {
        qr_code_url: qrCodeData.fileUrl
      },
      message: '重新生成二维码成功'
    });
  } catch (error) {
    logger.error('重新生成二维码失败:', error);
    res.status(500).json({ 
      message: error.message || '重新生成二维码失败'
    });
  }
};

// 切换证书状态
exports.toggleStatus = async (req, res) => {
  try {
    const { id } = req.params;
    const certificate = await Certificate.findByPk(id);
    
    if (!certificate) {
      return res.status(404).json({
        code: 404,
        message: '证书不存在'
      });
    }
    
    // 切换状态
    certificate.status = certificate.status === 'active' ? 'inactive' : 'active';
    await certificate.save();
    
    res.json({
      code: 200,
      message: `证书已${certificate.status === 'active' ? '启用' : '停用'}`,
      data: certificate
    });
  } catch (error) {
    logger.error('Toggle certificate status error:', error);
    res.status(500).json({
      code: 500,
      message: '切换证书状态失败'
    });
  }
}; 